package com.szm.mvc.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author 邵智民
 * @ClassName GenericsUtils.java
 * @Description
 */
public class GenericsUtils {

	private GenericsUtils() {
		
	}

	/**
	 * @author 邵智民
	 * @Description 默认的方法，找出第一个声明的泛型
	 * @param clazz
	 * @return 
	 */
	public static Class getGenericClass(Class clazz) {
		return getGenericClass(clazz, 0);
	}

	/**
	 * @author 邵智民
	 * @Description 根据class 泛型索引获取声明的泛型
	 * @param clazz
	 * @param index
	 * @return 
	 */
	public static Class getGenericClass(Class clazz, int index) {
		Type genType = clazz.getGenericSuperclass();

		if (genType instanceof ParameterizedType) {
			Type[] params = ((ParameterizedType) genType)
					.getActualTypeArguments();

			if ((params != null) && (params.length >= (index - 1))) {
				return (Class) params[index];
			}
		}
		return null;
	}

	/**
	 * @author 邵智民
	 * @Description 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
	 * @param clazz
	 * @return 
	 */
	public static Class getSuperClassGenricType(Class clazz) {
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * @author 邵智民
	 * @Description 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
	 * @param clazz
	 * @param index
	 * @return 
	 */
	public static Class getSuperClassGenricType(Class clazz, int index) {

		Type genType = clazz.getGenericSuperclass();

		if (!(genType instanceof ParameterizedType)) {
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0) {
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			return Object.class;
		}
		return (Class) params[index];
	}

}
